"""
认证相关工具函数
"""
import base64
import hmac
import hashlib
import datetime
from flask import current_app

def generate_token(user_id):
    """生成token"""
    timestamp = str(int(datetime.datetime.utcnow().timestamp()))
    data = f"{user_id}:{timestamp}"
    signature = hmac.new(
        current_app.config['JWT_SECRET_KEY'].encode('utf-8'),
        data.encode('utf-8'),
        hashlib.sha256
    ).hexdigest()
    token = base64.b64encode(f"{data}:{signature}".encode('utf-8')).decode('utf-8')
    return token

def verify_token(token):
    """验证token"""
    try:
        decoded = base64.b64decode(token.encode('utf-8')).decode('utf-8')
        user_id, timestamp, signature = decoded.split(':')
        
        # 检查token是否过期
        token_time = datetime.datetime.fromtimestamp(int(timestamp))
        if datetime.datetime.utcnow() - token_time > current_app.config['JWT_ACCESS_TOKEN_EXPIRES']:
            return None
            
        # 验证签名
        data = f"{user_id}:{timestamp}"
        expected_signature = hmac.new(
            current_app.config['JWT_SECRET_KEY'].encode('utf-8'),
            data.encode('utf-8'),
            hashlib.sha256
        ).hexdigest()
        
        if hmac.compare_digest(signature, expected_signature):
            return int(user_id)
        return None
    except:
        return None

